#!/bin/bash -eu
#
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

source /opt/c2d/c2d-utils || exit 1

mysql_matomo_db_name="<%= node['matomo']['db']['name'] %>"
mysql_matomo_username="<%= node['matomo']['db']['username'] %>"
mysql_matomo_first_password="<%= node['matomo']['db']['password'] %>"

declare -r mysql_matomo_db_name
declare -r mysql_matomo_username
declare -r mysql_matomo_first_password

mysql_matomo_new_password="$(get_attribute_value "mysql-matomouser-password")"
matomo_admin_email="$(get_attribute_value "matomo-admin-email")"
matomo_admin_password="$(get_attribute_value "matomo-admin-password")"

declare -r mysql_matomo_new_password
declare -r matomo_admin_email
declare -r matomo_admin_password

# Change the MySQL user password
mysqladmin -u "${mysql_matomo_username}" \
  -p"${mysql_matomo_first_password}" \
  password "${mysql_matomo_new_password}"

sed -i "s/${mysql_matomo_first_password}/${mysql_matomo_new_password}/" \
  /var/www/html/config/config.ini.php

# Calculate the admin's password hash in the way that Matomo
# recognizes it correctly
matomo_admin_password_hash="$( php -r "echo password_hash(md5('${matomo_admin_password}'), PASSWORD_DEFAULT);" )"
declare -r matomo_admin_password_hash

mysql -u "${mysql_matomo_username}" \
  -p"${mysql_matomo_new_password}" \
  -D "${mysql_matomo_db_name}" \
  -e "UPDATE user SET password = '${matomo_admin_password_hash}', email = '${matomo_admin_email}' WHERE login = 'admin'"
